<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use fast\Random;
use think\captcha\Captcha;
use think\Session;


require_once (ROOT_PATH . 'vendor/smssdk/SmsApi.php');

/**
 * 手机短信接口
 */
class Sms extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发送验证码前奏
     */
    public function before_send()
    {
        $sms_verify = Random::alnum(64);
        Session::delete('sms_verify');
        Session::set('sms_verify',$sms_verify);
        $this->success('发送验证码前的验证',['sms_verify' => $sms_verify]);
    }

    /**
     * 返回图形验证码
     */
    public function get_captcha_image()
    {
        //$captcha = new Captcha();
        echo captcha_img();
        //return $captcha->entry();
    }

    /**
     * 检测图形验证码
     */
    public function check_captcha_image()
    {
        $verify_code = $this->request->request('verify_code');
        $captcha = new Captcha();
        if (!$captcha->check($verify_code))
        {
            $this->error('图形验证码不正确');
        }
    }


    /**
     * 发送验证码
     */
    public function send()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $sms_verify = $this->request->request('sms_verify');
        //  发送短信前的验证
        if (!$sms_verify || $sms_verify != Session::get('sms_verify'))
        {
            $this->error('验证失败');
        }
        Session::delete('sms_verify');

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        //  检测手机号是否注册等
        if ($event) {
            $userinfo = db('user')->where(['phone'=>$mobile,'delstatus'=>1])->find();
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            }
        }
        //  发送短信
        $A_Sms= new \SmsApi();
        $res = $A_Sms ->send($mobile);
        return json (['data'=>'','code'=>$res['status'],'msg'=>$res['info']]);
    }

    /**
     * 检测验证码
     */
    public function check()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->request("captcha");


        $A_Sms= new \SmsApi();
        $verifyPhone = $A_Sms ->checkAppCode($mobile, $captcha, $event);

        if (!$verifyPhone)
        {
            return false;
        }
        return true;

        /*if(!$verifyPhone){
            $this->error('手机验证码输入有误');
            //return json (['data'=>'','code'=>-4,'msg'=>'手机验证码输入有误']);
        }
        $this->success('验证成功');*/
    }



//////////////////////////////////////////////////

    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $sms_verify 从 before_send() 获取的验证串
     */
    public function send_bak()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $sms_verify = $this->request->request('sms_verify');
        //  发送短信前的验证
        if (!$sms_verify || $sms_verify != Session::get('sms_verify'))
        {
            $this->error('验证失败');
        }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } else if (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::send($mobile, NULL, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败'));
        }
    }


    /**
     * 检测验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check_bak()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->request("captcha");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($event) {
            $userinfo = User::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } else if (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }
    }

}
